<script setup>
import { ElMessage } from 'element-plus'
import Area from '@/components/Area'
import {pinyin,postcode} from '@/api'
const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  options: { type: Object, default: () => ({}) },
  disabled: Boolean,
  loadData: Boolean,
})

const emit = defineEmits(['update:modelValue'])

// 表单处理
const formRef = ref()
const form = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})
const validate = async () => {
  return new Promise(resolve => {
    formRef?.value.validate((valid, fields) => {
      resolve({ model: 'basic', name: '基础信息', success: valid, message: fields })
    })
  })
}

const addAddress = () => {
  form.value.factory_address_list.push({
    default_account: 2,
    factory_address: "",
    factory_area_id: [],
    factory_area_name: []
  })
}

const addressChange = (idx) => {
  form.value.factory_address_list.forEach((d, i) => {
    d.default_account = idx === i ? 1 : 2
  })
}

const addressRemove = (i) => {
  form.value.factory_address_list.splice(i, 1)
  if (!form.value.factory_address_list.some(d => d.default_account === 1)) {
    form.value.factory_address_list[0].default_account = 1
  }
}

const areaChange = val => {
  // pinyin(val).then(res => {
  //   form.value.english_address = res.data
  // })
}
const handleSupplierEn = (isClick=0) => {
  const supplierName = form.value?.supplier_name;
  if (!supplierName&&isClick) {
    return ElMessage.warning("请维护供应商中文名称后再填充!");
  }
  getPinYin(
    [{ convert_string: supplierName }],
    ["supplier_en_name"]
  );
};
const handleAddressEn = (isClick=0) => {
  const areaNames = form.value?.company_area_name || [];
  if (!areaNames.length&&isClick) {
    return ElMessage.warning("请维护公司区域名称后再填充!");
  }
  const convertStrings = [
    ...areaNames.map((item) => ({ convert_string: item })),
    { convert_string: form.value?.company_address || "" },
  ];
  getPinYin(
    convertStrings,
    ["province_en_name", "city_en_name", "district_en_name", "english_address"]
  );
};
const getPostcode = async(isClick=0) =>{
  try {
    if(!form.value?.company_area_id?.length){
      if(isClick){
        ElMessage.warning('请维护公司地址后，再点击自动填充!');
      }
      form.value.zip_code = null
      return;
    }
    const {data} = await postcode(form.value?.company_area_id[1])
    form.value.zip_code = data||null
  } catch (error) {
    ElMessage.error('获取邮编失败，请稍后重试!');   
  }
}
const getPinYin = async(convertStrings,fields=[])=>{
  try {
    const {data} = await pinyin(convertStrings)
    fields.forEach((field, index) => {
      form.value[field] = data[index]?.pin_yin || null;
    });
  } catch (error) {
    ElMessage.error('获取拼音失败，请稍后重试!');  
  }
}
const clearValidate = () => {
  formRef?.value?.clearValidate()
}
const resetFields = () => {
  formRef?.value?.resetFields()
}
defineExpose({ validate, clearValidate, resetFields, formRef })
</script>

<template>
  <el-form ref="formRef" :model="form" label-position="top" :disabled="disabled" :label-width="160">
    <div class="grid grid-cols-4 gap-x-3">
      <el-form-item label="供应商ID" prop="supplier_code">
        <el-input v-model="form.supplier_code" disabled placeholder="请输入" />
      </el-form-item>
      <el-form-item label="供应商编码" prop="supplier_coding">
        <el-input v-model="form.supplier_coding" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplier_name"
        :rules="[{ required: true, message: '供应商名称不能为空', trigger: 'blur' }]">
        <el-input v-model="form.supplier_name" placeholder="请输入" @change="handleSupplierEn"/>
      </el-form-item>
      <el-form-item label="法人代表" prop="legal_person">
        <el-input v-model="form.legal_person" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="统一社会信用代码" prop="social_code">
        <el-input v-model="form.social_code" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="注册时间" prop="register_time">
        <el-date-picker v-model="form.register_time" class="w-full" value-format="YYYY-MM-DD" placeholder="选择日期时间" />
      </el-form-item>
      <el-form-item label="分支机构信息" prop="branch_offices">
        <el-input v-model="form.branch_offices" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="公司性质" prop="company_nature">
        <VSelect v-model="form.company_nature" :options="options.company_nature" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="公司类别" prop="company_category">
        <VSelect v-model="form.company_category" :options="options.company_category" placeholder="请选择" filterable
          clearable class="w-full" />
      </el-form-item>
      <el-form-item label="供应商主营品类" prop="business_category">
        <VCascader v-model="form.business_category" placeholder="产品分类" type="2" multiple collapse-tags filterable
          clearable class="w-full" />
      </el-form-item>
      <el-form-item label="供应商状态" prop="status" :rules="[{ required: true, message: '供应商状态不能为空', trigger: 'change' }]">
        <VSelect v-model="form.status" :options="options.status" placeholder="请选择" filterable :clearable="false"
          class="w-full" />
      </el-form-item>
      <el-form-item label="分管部门">
        <VCascader v-model="form.department_id" placeholder="请选择" type="1" class="w-full" />
      </el-form-item>
      <el-form-item label="供应商等级" prop="supplier_level">
        <VSelect v-model="form.supplier_level" :options="options.supplier_level" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="税务登记号" prop="tax_no">
        <el-input v-model="form.tax_no" placeholder="请输入" :maxlength="200" />
      </el-form-item>
      <el-form-item label="供应商网址" prop="supplier_url">
        <el-input v-model="form.supplier_url" placeholder="请输入" :maxlength="200" />
      </el-form-item>
      <el-form-item label="系统供应商账号" prop="supplier_account">
        <el-input v-model="form.supplier_account" placeholder="请输入" :maxlength="200" />
      </el-form-item>
      <el-form-item label="邮编" prop="zip_code">
        <v-group>
          <el-input v-model="form.zip_code" placeholder="请输入" :maxlength="200" />
          <el-button type="primary" class="px-2" @click="getPostcode(1)">自动填充</el-button>
        </v-group>
      </el-form-item>
      <el-form-item label="是否黑名单" prop="is_blacklist">
        <VSelect v-model="form.is_blacklist" :options="options.is_label" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="公司地址" prop="company_area_id"
        :rules="[{ required: !loadData, message: '公司地址不能为空', trigger: 'change' }]" class="col-span-2">
        <Area v-model="form" field="company" @change="(val)=>{handleAddressEn();getPostcode()}"/>
      </el-form-item>
      <el-form-item label="工厂地址" :prop="['factory_address_list', '0', 'factory_area_id']"
        :rules="[{ required: !loadData, message: '工厂地址不能为空', trigger: 'change' }]" class="col-span-2">
        <template #label>
          工厂地址 <el-button type="primary" link @click="addAddress">添加</el-button>
        </template>
        <div class="flex flex-col gap-1">
          <div v-for="(d, i) in form.factory_address_list" :key="i" class="grid"
            :style="{ 'grid-template-columns': 'repeat(14, minmax(0, 1fr))' }">
            <el-radio :key="i" v-model="d.default_account" :value="1" @change="addressChange(i)">&nbsp;</el-radio>
            <Area v-model="form.factory_address_list[i]" field="factory" class="col-span-12" />
            <el-button v-if="form.factory_address_list.length > 1" link type="primary" class="col-span-1"
              @click="addressRemove(i)">移除</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="退货地址" class="col-span-2">
        <Area v-model="form" field="return" />
      </el-form-item>
      <el-form-item label="供应商英文名称" prop="supplier_en_name" class="col-span-2">
        <v-group class="w-full">
          <el-input v-model="form.supplier_en_name" placeholder="请输入" class="w-full"/>
          <el-button type="primary" class="px-2" @click="handleSupplierEn">自动填充</el-button>
        </v-group>
        <div><el-checkbox v-model="form.is_en_name_push" :true-value="2" :false-value="1">修改审核通过后更新改供应商所有产品的欧英代对应信息</el-checkbox></div>
      </el-form-item>
      <el-form-item label="供应商英文地址" prop="english_address" class="col-span-2">
        <v-group class="w-full">
          <el-input v-model="form.province_en_name " placeholder="省" class="w-[250px]"/>
          <el-input v-model="form.city_en_name" placeholder="市" class="w-[250px]"/>
          <el-input v-model="form.district_en_name" placeholder="区" class="w-[250px]"/>
          <el-input v-model="form.english_address" placeholder="详细地址" />
          <el-button type="primary" class="px-2" @click="handleAddressEn(1)">自动填充</el-button>
        </v-group>
        <div><el-checkbox v-model="form.is_english_address_push" :true-value="2" :false-value="1">修改审核通过后更新改供应商所有产品的欧英代对应信息</el-checkbox></div>
      </el-form-item>
      <el-form-item label="开发人员" prop="develop_id">
        <VCascader v-model="form.develop_id" placeholder="人员" class="w-full"
          @change="({ labels }) => form.develop_name = labels" />
      </el-form-item>
      <el-form-item label="是否为临时供应商" prop="is_temporary">
        <VSelect v-model="form.is_temporary" :options="options.is_temporary" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="是否支持函调">
        <VSelect v-model="form.is_investigate" :options="options.is_investigate" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="是否有自己的财务">
        <VSelect v-model="form.is_has_finance" :options="options.is_has_finance" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="营业执照地址是否相符">
        <VSelect v-model="form.is_license_same" :options="options.is_license_same" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="供应商中文名称" class="col-span-2">
        <el-input v-model="form.supplier_cn_name" placeholder="请输入"/>
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="col-span-full">
        <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" placeholder="请输入" />
      </el-form-item>
    </div>
  </el-form>
</template>
